package cmd

import (
	"github.com/gin-gonic/gin"
	"xlq-demo/library/config"
	"xlq-demo/app/api/route"
	"xlq-demo/library/util"
)

func RunApi() {
	app := gin.New()
	if config.Config.Base.Debug {
		gin.SetMode(gin.DebugMode)
	}
	app.Use(gin.Logger(),gin.Recovery(),CheakHeader,CheckAuth)

	//v1
	route.Setv1(app)

	addr := config.Config.Api.Ip+":"+config.Config.Api.Port
	app.Run(addr)
}

//跨域处理
func CheakHeader(ctx *gin.Context) {
	//验证content-type
	if ctx.ContentType() != "application/json" {
		ctx.Status(500)
		ctx.Abort()
	}
	//跨域
	origin := ctx.Request.Header.Get("origin")
	if len(origin) == 0 {
		origin = ctx.Request.Header.Get("Origin")
	}
	ctx.Writer.Header().Set("Access-Control-Allow-Origin", origin)
	ctx.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
	ctx.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
	ctx.Writer.Header().Set("Access-Control-Allow-Methods", "OPTIONS, GET, POST")
	ctx.Writer.Header().Set("Content-Type", "application/json; charset=utf-8")
	if ctx.Request.Method == "OPTIONS" {
		ctx.AbortWithStatus(204)
		ctx.Abort()
	}
	ctx.Next()
}

//白名单校验
func CheckAuth(ctx *gin.Context) {
	uri := ctx.Request.URL.Path
	noAuths := route.NoAuthUri()
	if util.StringInSlice(uri,noAuths) {
		ctx.Next()
		return
	}

	//开始鉴权


	ctx.Next()
}

